package main

import (
	"context"
	"fmt"
	"sync"
	"time"
)

var wg sync.WaitGroup

func worker(ctx context.Context) {

	for {
		go watch(ctx, "wangcai")
		select {
		case <-ctx.Done():
			fmt.Println("ready to exit")
			wg.Done()
			return
		default:
			fmt.Println("working")
			time.Sleep(time.Second)
		}
	}
}

// 慢响应, 是比快速失败还要可怕的东西
func watch(ctx context.Context, name string) {
	for {
		select {
		case <-ctx.Done():
			fmt.Println("watch dog ", name, " ready to exit")
			return
		}
	}
}

func main() {
	wg.Add(1)
	ctx, cancel := context.WithCancel(context.Background())
	go worker(ctx)
	time.Sleep(time.Second * 3)
	cancel()
	wg.Wait()
	time.Sleep(time.Millisecond)
	fmt.Println("over")
}
